from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
import redis
import pymysql
import logging

pymysql.install_as_MySQLdb()

db = SQLAlchemy()
migrate = Migrate()
redis_client = None


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    # 配置应用日志
    if not app.debug:
        file_handler = logging.FileHandler('app.log', encoding='utf-8')
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('应用启动')

    db.init_app(app)
    migrate.init_app(app, db)

    # 初始化Redis连接
    try:
        global redis_client
        redis_client = redis.Redis(
            host=app.config["REDIS_HOST"],
            port=app.config["REDIS_PORT"],
            db=app.config["REDIS_DB"],
            password=app.config.get("REDIS_PASSWORD"),
            decode_responses=True,
        )
        redis_client.ping()  # 测试连接
        app.logger.info('Redis连接成功')
    except redis.RedisError as e:
        app.logger.error(f'Redis连接失败: {str(e)}')
        redis_client = None

    # 初始化CUDA环境
    if app.config.get('USE_GPU', False):
        try:
            import cupy as cp
            device = cp.cuda.Device(app.config.get('GPU_DEVICE', 0))
            device.use()
            app.logger.info(f'CUDA初始化成功，使用设备: {device.id}')
        except Exception as e:
            app.logger.error(f'CUDA初始化失败: {str(e)}')
            app.logger.warning('将使用CPU模式运行')

    from . import views
    # 导入模型和适配器
    from . import models, new_models, db_adapter, care_utils

    # 应用Plan类的补丁
    try:
        from . import scheduler_adapter
        original_methods = scheduler_adapter.apply_patches()
        app.logger.info('已应用Plan类的补丁')
    except Exception as e:
        app.logger.error(f'应用Plan类的补丁失败: {str(e)}')

    views.init_app(app)

    # 已完全移除自动排班功能

    return app
